package com.lnsf.bookstore.web.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lnsf.bookstore.common.exception.RException;
import com.lnsf.bookstore.common.util.DateTimeUtils;
import com.lnsf.bookstore.system.order.dao.OrderMapper;
import com.lnsf.bookstore.system.order.vo.Order;
import com.lnsf.bookstore.system.orderDetail.vo.OrderDetail;
import com.lnsf.bookstore.web.address.dao.ApiAddressMapper;
import com.lnsf.bookstore.web.address.vo.ApiAddress;
import com.lnsf.bookstore.web.cart.dao.ApiCartMapper;
import com.lnsf.bookstore.web.cart.vo.ApiCart;
import com.lnsf.bookstore.web.coupon.dao.ApiCouponMapper;
import com.lnsf.bookstore.web.coupon.vo.ApiCoupon;
import com.lnsf.bookstore.web.order.dao.ApiOrderMapper;
import com.lnsf.bookstore.web.order.service.ApiOrderService;
import com.lnsf.bookstore.web.order.vo.ApiOrder;
import com.lnsf.bookstore.web.orderDetail.dao.ApiOrderDetailMapper;
import com.lnsf.bookstore.web.orderDetail.service.ApiOrderDetailService;
import com.lnsf.bookstore.web.orderDetail.vo.ApiOrderDetail;
import com.lnsf.bookstore.web.user.vo.ApiUser;
import com.lnsf.bookstore.web.userCoupon.dao.ApiUserCouponMapper;
import com.lnsf.bookstore.web.userCoupon.vo.ApiUserCoupon;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

@Service
@Transactional
public class ApiOrderServiceImpl implements ApiOrderService {

    @Autowired
    private ApiOrderMapper apiOrderMapper;
    @Autowired
    private ApiAddressMapper apiAddressMapper;
    @Autowired
    private ApiCartMapper apiCartMapper;
    @Autowired
    private ApiCouponMapper apiCouponMapper;
    @Autowired
    private ApiOrderDetailMapper apiOrderDetailMapper;
    @Autowired
    private ApiUserCouponMapper apiUserCouponMapper;


    @Override
    public List<ApiOrder> queryList(Map<String, Object> map) {
        if(map.get("page")!=null && map.get("limit")!=null){
            PageHelper.startPage((Integer)map.get("page"),(Integer) map.get("limit"));
        }

        return apiOrderMapper.queryList(map);
    }

    @Override
    public int update(ApiOrder apiOrder) {
        return apiOrderMapper.updateByPrimaryKeySelective(apiOrder);
    }

    @Override
    public Map queryTotal(Map<String, Object> map) {
        return apiOrderMapper.queryTotal4Map(map);
    }

    @Override
    public ApiOrder queryObject(Integer id) {
        return apiOrderMapper.queryObject(id);
    }

    @Override
    public Map submit(JSONObject jsonObject, ApiUser apiUser) {
        Map resultObj = new HashMap();
        Map<String,Object> jsonMap = (Map<String, Object>) jsonObject.get("data");
        List<ApiCart> apiCartList = JSONObject.parseArray(jsonMap.get("cartList").toString(),ApiCart.class);
        String content = (String) jsonMap.get("content");
        BigDecimal freightPrice = new BigDecimal(jsonMap.get("freightPrice").toString());
        Integer couponId = (Integer) jsonMap.get("couponId");
        ApiAddress apiAddress1 = JSONObject.parseObject(jsonMap.get("address").toString(),ApiAddress.class);

        ApiAddress apiAddress = apiAddressMapper.selectByPrimaryKey((Integer) jsonMap.get("addressId"));

        //获取要购买的商品
        Map param = new HashMap();
        param.put("userId", apiUser.getUserId());
        param.put("checked", 1);
        List<ApiCart> checkedBooksList = apiCartMapper.queryList(param);
        if (null == checkedBooksList) {
            resultObj.put("errno", 400);
            resultObj.put("errmsg", "请选择商品");
            return resultObj;
        }

        //统计商品总价
        BigDecimal booksTotalPrice = new BigDecimal(0.00);
        Integer bookCount = 0;
        for (ApiCart cartItem : checkedBooksList) {
            bookCount += cartItem.getNumber();
            booksTotalPrice = booksTotalPrice.add(cartItem.getRetailPrice().multiply(new BigDecimal(cartItem.getNumber())));
        }

        //获取订单使用的优惠券
        BigDecimal couponPrice = new BigDecimal(0.00);
        ApiCoupon apiCoupon = null;
        if (null != couponId && 0 != couponId) {
            apiCoupon = apiCouponMapper.queryObject(couponId);
            if (null != apiCoupon && null != apiCoupon.getParPrice()) {
                couponPrice = apiCoupon.getParPrice();
            }
        }
        //订单价格计算
        BigDecimal orderTotalPrice = booksTotalPrice.add(freightPrice); //订单的总价

        BigDecimal actualPrice = orderTotalPrice.subtract(couponPrice);  //减去其它支付的金额后，要实际支付的金额

        //订单信息添加
        ApiOrder apiOrder = new ApiOrder();
        apiOrder.setOrderNo(DateTimeUtils.genSerialNo());
        apiOrder.setUserId(apiUser.getUserId());
        //收货地址和运费
        apiOrder.setReceiver(apiAddress.getReceivername());
        apiOrder.setMobile(apiAddress.getPhone());
        apiOrder.setAddress(apiAddress.getAreaInfoCode()+apiAddress.getStreet());
        apiOrder.setBuyCount(bookCount);
        apiOrder.setCreateTime(new Date());
        apiOrder.setFreightPrice(freightPrice);
        apiOrder.setCouponId(couponId);
        apiOrder.setActualPrice(actualPrice);
        apiOrder.setBookTotalPrice(booksTotalPrice.toString());
        apiOrder.setBuyerRemarks(content);

        //付款状态
        apiOrder.setOrderStatus(1);
        apiOrder.setLogisticsId(0);
        apiOrder.setPayStatus(0);

        //开启事务，插入订单信息和订单商品
        apiOrderMapper.insertSelective(apiOrder);
        if (null == apiOrder.getId()) {
            resultObj.put("errno", 1);
            resultObj.put("errmsg", "订单提交失败");
            return resultObj;
        }

        //订单详情信息添加
        List<ApiOrderDetail> apiOrderDetailList = new ArrayList<ApiOrderDetail>();
        for (ApiCart apiCart : checkedBooksList) {
            ApiOrderDetail apiOrderDetail = new ApiOrderDetail();
            apiOrderDetail.setOrderId(apiOrder.getId());
            apiOrderDetail.setBookId(apiCart.getBookId());
            apiOrderDetail.setAmount(apiCart.getRetailPrice().multiply(new BigDecimal(apiCart.getNumber())));
            apiOrderDetail.setQuantity(apiCart.getNumber());
            apiOrderDetail.setSalePrice(apiCart.getRetailPrice());
            apiOrderDetail.setDealPrice(apiCart.getMarketPrice());
            apiOrderDetailMapper.insertSelective(apiOrderDetail);
        }
        //清空已购买的商品
        apiCartMapper.deleteByCart(apiUser.getUserId(), 1);
        resultObj.put("errno", 0);
        resultObj.put("errmsg", "订单提交成功");
        Map orderInfoMap = new HashMap();
        orderInfoMap.put("apiOrder", apiOrder);
        resultObj.put("data", orderInfoMap);

        // 优惠券标记已用
        if(apiCoupon!=null){
            if (!StringUtils.isEmpty(apiCoupon.getUserCouponNum().toString())) {
                ApiUserCoupon userCouponVo = apiUserCouponMapper.queryByCouponNumber(apiCoupon.getUserCouponNum().toString());
                if (null != userCouponVo && null == userCouponVo.getOrderId()) {
                    userCouponVo.setUsedTime(new Date());
                    userCouponVo.setOrderId(apiOrder.getId());
                    userCouponVo.setStatus(1);
                    apiUserCouponMapper.updateByPrimaryKeySelective(userCouponVo);
                }
            }
        }

        return resultObj;
    }
}
